var formInputs2;
var testdata;

// 数组小数全部相加方法//////////
function arrayFloatAdd(array) {
  var afa = 0;
  for (var g = 0; g < array.length; g++) {
    afa = FloatAdd(array[g], afa);
  }
  //   console.log(afa);
  return afa;
}

//封装一个处理表单序列化数据格式
function formatData(array) {
  var data = {};
  //处理需要提交的数据
  var conut = 0;
  $.each(array, function (index, item) {
    data[item.name] = item.value;
    conut++;
  });
  // data['length'] = conut;
  return data;
}

// -------------------计算刷新----------------------//
var trsBoxNames;

function scal(e) {
  //监听页面输入或焦点事件后触发计算
  try {
    //------------1、计算钣金结构成本小计--------------------//
    var banjingTR = $("#tbody0 > tr"); //获取全部钣金TRlist
    trsBoxNames = []; //声明柜型变量容器
    var trsBanjins = []; //全部柜型钣金成本集合
    for (var i = 0; i < banjingTR.length; i++) {
      var TDS = $(banjingTR[i]).find("td");
      var FloatTota = 0;
      trsBoxNames.push($(TDS[1]).find("input").val()); //存起来全部柜型名
      //   trsBanjins.push($(TDS[12]).find("input").val());
      //   console.log("trsBoxNames", trsBoxNames);
      for (var t = 2; t < TDS.length - 2; t++) {
        var tdValue = $(TDS[t]).children().val(); //获取材料费
        var toFloat = parseFloat(tdValue).toFixed(2); //转整数保留2位小数
        FloatTota = FloatAdd(toFloat, FloatTota); //累加
      }
      $(TDS).eq(11).children().val(FloatTota); //写出累加的含税钣金总成本
      var buhanshuibanjin = parseFloat(FloatTota * 0.87).toFixed(2); //计算不含税钣金成本
      $(TDS).eq(12).children().val(buhanshuibanjin); //写出不含税钣金总成本
      trsBanjins.push(buhanshuibanjin); //集合钣金不含税成本
    }

    // -----------------2、电控件计算-----------------------//
    var deviceTbody = $(".deviceTbody");
    var trsDiankongs = []; //全部柜型电控成本集合
    for (var q = 0; q < deviceTbody.length; q++) {
      //循环每个表
      // console.log("deviceTbody", deviceTbody.length);
      var dianKongTRS = $(deviceTbody[q]).find("tr"); //   获取每个表的全部TR
      // console.log("dianKongTRS", dianKongTRS.length);
      var FloatTota2 = 0;
      var toFloat2;
      for (var ii = 0; ii < dianKongTRS.length; ii++) {
        //循环遍历全部tr
        var TDS2 = $(dianKongTRS[ii]).find("td"); //获取全部td
        var tds2Conut = $(TDS2).eq(4).children().val() | 0;
        var tds2Price = $(TDS2).eq(5).children().val() | 0;
        var dts2PC = tds2Conut * tds2Price;
        toFloat2 = parseFloat(dts2PC).toFixed(2);
        $(TDS2).eq(6).children().val(toFloat2); //写小计
        FloatTota2 = FloatAdd(toFloat2, FloatTota2); //累计小计保留小数位
        var diankongPriceTotals = $(deviceTbody).eq(q).next();
        var diankongTrTotal = $(diankongPriceTotals).find("tr");
        var TDS22 = $(diankongTrTotal).find("td"); //获取统计tr下的td
        // console.log(toFloat2, FloatTota2);
        $(TDS22).eq(1).children().val(FloatTota2); //写出含税合计
        var buhanshuidiankog = parseFloat(FloatTota2 * 0.87).toFixed(2);
        $(TDS22).eq(3).children().val(buhanshuidiankog); //写出不含税合计
        trsDiankongs.push(buhanshuidiankog || 0);
      }
      //   console.log(trsDiankongs);
      //   console.log(trsBoxNames, trsBanjins, trsDiankongs);
    }
    // ------------------电控结束-----------------------------------------/

    //-----------------------三、材料成本汇总-----------------------------//
    var costTotalTbodyTR = $("#costTotalTbody tr");
    // console.log("costTotalTbodyTR", costTotalTbodyTR.length);
    var hanshuichengben, buhanshuichengben;
    // var buHanShuiDidankongInput = $(".buHanShuiDidankong");
    // console.log(buHanShuiDidankongInput);
    var buhanshuichengbens = [];
    for (var b = 0; b < costTotalTbodyTR.length; b++) {
      //   var buHanShuiDidankong = $(buHanShuiDidankongInput[b]).html() || 0;
      //   console.log(buHanShuiDidankong);
      var rgtds = $(costTotalTbodyTR[b]).find("td"); //获取当前行的全部TD
      $(rgtds)
        .eq(1)
        .find("input")
        .val(trsBoxNames[b] || "未填写"); //写出全部柜型名称
      //   console.log(trsBoxNames, trsBanjins, trsDiankongs);
      $(rgtds)
        .eq(2)
        .find("input")
        .val(trsBanjins[b] || 0); //写每个柜型的钣金不含税成本
      //   console.log(trsDiankongs[b] || 0);
      $(rgtds)
        .eq(3)
        .find("input")
        .val(trsDiankongs[b] || 0); //写每个柜型的电控不含税成本
      var xiancai = parseFloat($(rgtds).eq(4).find("input").val() || 0); //获取线材
      var baocai = parseFloat($(rgtds).eq(5).find("input").val()) || 0; //获取包材
      var qitafei = parseFloat($(rgtds).eq(6).find("input").val()) || 0; //获取其他费用
      var s1 = FloatAdd(parseFloat(trsBanjins[b]), parseFloat(trsDiankongs[b]) | 0);
      var s2 = FloatAdd(s1, xiancai);
      var s3 = FloatAdd(s2, baocai);
      buhanshuichengben = FloatAdd(s3, qitafei);
      $(rgtds).eq(8).find("input").val(buhanshuichengben);
      hanshuichengben = parseFloat(buhanshuichengben * 1.13).toFixed(2);
      $(rgtds).eq(7).find("input").val(hanshuichengben);
      buhanshuichengbens.push(buhanshuichengben);
      //   console.log("buhanshuichengbens:", buhanshuichengbens);
      //   //   console.log(hanshuichengben, buhanshuichengben);
    }

    // -------------------------四、人工计算------------------------//
    var renGongTbody = $("#renGongTbody tr"); //获取人工body TR元素集合
    var buhansrgzfs = [];
    for (var a = 0; a < renGongTbody.length; a++) {
      var rgtds = $(renGongTbody[a]).find("td"); //获取全部TD
      // 计算工时合计
      var rgTimes1 = parseFloat($(rgtds[3]).find("input").val()) + parseFloat($(rgtds[4]).find("input").val()) + parseFloat($(rgtds[5]).find("input").val());
      var rgTimes2 = parseFloat($(rgtds[5]).find("input").val()) + parseFloat($(rgtds[6]).find("input").val()) + parseFloat($(rgtds[7]).find("input").val()) + parseFloat($(rgtds[8]).find("input").val());
      var RGTimes = parseFloat((rgTimes1 + rgTimes2) / 60).toFixed(2);
      // console.log("RGTimes", RGTimes);
      $(rgtds).eq(9).find("input").val(RGTimes);
      var RGfei = parseFloat(RGTimes * 34).toFixed(2);
      $(rgtds).eq(10).find("input").val(RGfei);
      var zhizaofei = parseFloat(RGfei * 0.49).toFixed(2);
      $(rgtds).eq(11).find("input").val(zhizaofei);
      var rgzhizaofei = FloatAdd(RGfei, zhizaofei);
      $(rgtds).eq(12).find("input").val(rgzhizaofei);
      buhansrgzfs.push(rgzhizaofei);
      //   console.log(rgzhizaofei);
      $(rgtds).eq(1).find("input").val(trsBoxNames[a]); //写出全部柜型
    }

    // --------------5、阶梯报价汇算 buhansrgzfs- buhanshuichengben--------------------//
    var jieTiPricelTbody = $("#jieTiPricelTbody tbody");
    var bhszcb = [];
    var hszcb = [];
    var dwbj = [];
    for (var c = 0; c < jieTiPricelTbody.length; c++) {
      //   console.log(jieTiPricelTbody.length);
      var jieTiPricelTbodyTRs = $(jieTiPricelTbody).eq(c).find("tr");
      //   console.log(jieTiPricelTbodyTRs.length);
      for (var d = 1; d < jieTiPricelTbodyTRs.length; d++) {
        var jieTiPricelTbodyTR = jieTiPricelTbodyTRs[d];
        // console.log(jieTiPricelTbodyTR);
        var jieTiPricelTbodyTRTDS = $(jieTiPricelTbodyTR).find("td");
        // console.log(jieTiPricelTbodyTRTDS.length);
        $(jieTiPricelTbodyTRTDS)
          .eq(1)
          .find("input")
          .val(trsBoxNames[d - 1]); //写出全部柜型名称
        $(jieTiPricelTbodyTRTDS)
          .eq(2)
          .find("input")
          .val(buhanshuichengbens[d - 1]); //写出全部不含税材料
        $(jieTiPricelTbodyTRTDS)
          .eq(3)
          .find("input")
          .val(buhansrgzfs[d - 1]); //写出全部不含税人工
        var buhanshuizongchengben = FloatAdd(buhanshuichengbens[d - 1], buhansrgzfs[d - 1]);

        // console.log(buhanshuizongchengben);
        $(jieTiPricelTbodyTRTDS).eq(4).find("input").val(buhanshuizongchengben); //写出单价不含税成本
        var zongchengbenhanshui = parseFloat(buhanshuizongchengben * 1.13).toFixed(2);
        // hszcb.push(zongchengbenhanshui);
        $(jieTiPricelTbodyTRTDS).eq(5).find("input").val(zongchengbenhanshui); //写出含税单价成本
        var maolilv = $(jieTiPricelTbodyTRTDS).eq(6).find("input").val();
        // console.log(maolilv);
        var maolilvbaojia = parseFloat(buhanshuizongchengben / ((100 - maolilv) / 100)).toFixed(2);
        // console.log(maolilvbaojia);
        $(jieTiPricelTbodyTRTDS).eq(7).find("input").val(maolilvbaojia); //写出毛利率报价
        var wuliufei = parseFloat($(jieTiPricelTbodyTRTDS).eq(8).find("input").val() | 0);
        var bangyunzhuaungxie = parseFloat($(jieTiPricelTbodyTRTDS).eq(9).find("input").val() | 0);
        var zhibaobaojia = parseFloat(maolilvbaojia * 0.02).toFixed(2);
        $(jieTiPricelTbodyTRTDS).eq(10).find("input").val(zhibaobaojia); //写出质保费
        var zhibao = parseFloat($(jieTiPricelTbodyTRTDS).eq(10).find("input").val() | 0);

        // console.log(buhanshuizongchengben, zongchengbenhanshui, wuliufei, bangyunzhuaungxie, zhibao);
        hszcb.push(parseFloat(parseFloat(zongchengbenhanshui) + wuliufei + bangyunzhuaungxie + zhibao).toFixed(2)); //累加全部成本
        bhszcb.push(
          //累加全部成本 材料 人工 物流 运输 质保
          parseFloat(parseFloat(buhanshuizongchengben) + wuliufei + bangyunzhuaungxie + zhibao).toFixed(2)
        );
        // console.log(hszcb);
        // console.log(bhszcb);
        var addData1 = FloatAdd(maolilvbaojia, wuliufei);
        var addData2 = FloatAdd(addData1, bangyunzhuaungxie);
        var addData3 = FloatAdd(addData2, zhibao);
        $(jieTiPricelTbodyTRTDS).eq(11).find("input").val(addData3);
        dwbj.push(addData3); //写出对外报价
      }
    }

    //--------------------六、硬件对外推荐报价--------------------------//
    var duiwaituijianbaojiaTR = $("#duiwaituijianbaojia tr");
    //   console.log(duiwaituijianbaojiaTR);
    var yjduiwaibaojia = [];
    var yjhscb = [];
    var cpCount = [];
    var salseTC = [];
    for (var e = 0; e < duiwaituijianbaojiaTR.length; e++) {
      var duiwaituijianbaojiaTRTDS = $(duiwaituijianbaojiaTR).eq(e).find("td");
      $(duiwaituijianbaojiaTRTDS).eq(1).find("input").val(trsBoxNames[e]); //写出全部柜型名称
      //  $(jieTiPricelTbodyTRTDS);
      // console.log(duiwaituijianbaojiaTRTDS);  hszcb
      $(duiwaituijianbaojiaTRTDS).eq(3).find("input").val(bhszcb[e]); //写出不含税总成本
      $(duiwaituijianbaojiaTRTDS).eq(4).find("input").val(hszcb[e]); //写出含税硬件总成本 单价
      yjhscb.push(hszcb[e]); //累计含税成本硬件
      var xstc = parseFloat(dwbj[e] * 0.05).toFixed(2);
      salseTC.push(xstc); //存储销售提成
      $(duiwaituijianbaojiaTRTDS).eq(5).find("input").val(xstc); //写出销售提成  报价的0.02
      var jinlirun = parseFloat(FloatSub(dwbj[e], hszcb[e])).toFixed(2);
      $(duiwaituijianbaojiaTRTDS).eq(6).find("input").val(jinlirun); //写出净利润
      var jinlilv = parseFloat((jinlirun / dwbj[e]) * 100).toFixed(2);
      $(duiwaituijianbaojiaTRTDS).eq(7).find("input").val(jinlilv); //写出净利率
      var shuliang = $(duiwaituijianbaojiaTRTDS).eq(8).find("input").val() | 0; //获取数量
      cpCount.push(shuliang); //存储各柜型数量
      var dwbjxj = parseFloat(parseInt(shuliang) * dwbj[e]).toFixed(2);
      $(duiwaituijianbaojiaTRTDS).eq(9).find("input").val(dwbjxj); //写出对外报价小计
      yjduiwaibaojia.push(dwbjxj); //硬件对外报价
      var jinglirunheji = parseFloat(jinlirun * shuliang).toFixed(2);
      $(duiwaituijianbaojiaTRTDS).eq(10).find("input").val(jinglirunheji); //写出净利润合计
    }

    //   ------------------7、技术服务费---------------------------//   $(serviceTbodyTRTDS).eq(5).find("input").val() | 0;
    var fwfduiwaibaojia = [];
    var kfzongchengben = [];
    var serviceTbodyTRS = $("#serviceTbody tr");
    for (var f = 0; f < serviceTbodyTRS.length; f++) {
      var serviceTbodyTRTDS = $(serviceTbodyTRS[f]).find("td");
      //   $(serviceTbodyTRTDS).eq(1).find("input").val(trsBoxNames[f]); //写出全部柜型名称
      //   console.log(serviceTbodyTRTDS);
      var kfTime = $(serviceTbodyTRTDS).eq(3).find("input").val() | 0;
      var kfCBDanJia = $(serviceTbodyTRTDS).eq(4).find("input").val() | 0;
      var kfcbJE = parseFloat(kfTime * kfCBDanJia).toFixed(2);
      kfzongchengben.push(kfcbJE); //开发服务费总成本累计
      $(serviceTbodyTRTDS).eq(5).find("input").val(kfcbJE);
      var kfBjDanjia = $(serviceTbodyTRTDS).eq(6).find("input").val() | 0; //开发报价单价
      var serviceBaojia = parseFloat(kfTime * kfBjDanjia).toFixed(2);
      $(serviceTbodyTRTDS).eq(7).find("input").val(serviceBaojia);
      fwfduiwaibaojia.push(serviceBaojia); //服务费对外报价累计
      var serviceRote = parseFloat(((serviceBaojia - kfcbJE) / serviceBaojia) * 100).toFixed(2);
      $(serviceTbodyTRTDS).eq(8).find("input").val(serviceRote);
    }

    // --------------------八、报价总计-----------yjduiwaibaojia-------fwfduiwaibaojia---- kfzongchengben----yjhscb--\\
    var cpzongbaojia = arrayFloatAdd(yjduiwaibaojia); //计算硬件总报价
    var outPrice1Totaltrs = $("#outPrice1Total").find("tr");
    var outPrice1TotaltrTds = $(outPrice1Totaltrs[0]).find("td");
    $(outPrice1TotaltrTds[1]).find("input").val(cpzongbaojia); //写出硬件总报价

    var fwufzongbaojia2 = arrayFloatAdd(fwfduiwaibaojia); //计算服务费总报价
    $(outPrice1TotaltrTds[2]).find("input").val(fwufzongbaojia2); //写出服务费总报价
    var yjhscbs = [];
    for (var h = 0; h < yjhscb.length; h++) {
      yjhscbs.push(yjhscb[h] * cpCount[h]);
    }
    var zongchengben = FloatAdd(arrayFloatAdd(kfzongchengben), arrayFloatAdd(yjhscbs)); //计算项目总共成本
    $(outPrice1TotaltrTds[3]).find("input").val(zongchengben); //写出总成本
    var zongbaojia = FloatAdd(cpzongbaojia, fwufzongbaojia2); //计算总报价合计
    $(outPrice1TotaltrTds[4]).find("input").val(zongbaojia); //写出总项目报价
    var zongmaolllv = parseFloat((FloatSub(zongbaojia, zongchengben) / zongbaojia) * 100).toFixed(2); //计算总毛利率
    $(outPrice1TotaltrTds[5]).find("input").val(zongmaolllv); //写出总项目报价
    var qtfybaojia = $(outPrice1TotaltrTds[6]).find("input").val() | 0; //获取其他外加费用
    var zongjinlirun = parseFloat(parseFloat(zongbaojia) + qtfybaojia - parseFloat(zongchengben)).toFixed(2); //计算总利润
    $(outPrice1TotaltrTds[7]).find("input").val(zongjinlirun); //写出总利润
    var salseTC2 = arrayFloatAdd(salseTC); //合计销售提成
    var zongjinlilv = parseFloat((FloatSub(zongjinlirun, salseTC2) / zongbaojia) * 100).toFixed(2); //计算总利率
    // console.log(zongjinlirun, salseTC2, zongbaojia, zongjinlilv);
    $(outPrice1TotaltrTds[8]).find("input").val(zongjinlilv); //写出总利率
    var duiwaizongbaojia = FloatAdd(zongbaojia, qtfybaojia); //计算总共报价对外
    $(outPrice1TotaltrTds[9]).find("input").val(duiwaizongbaojia); //写出总对外报价合计
    var salesTotalPrice = duiwaizongbaojia; //总对外报价
    $("input[name='salesTotalPrice']").val(salesTotalPrice); //写出总对外报价

    // console.log(zongbaojia, qtfybaojia, zongchengben);
    // console.log(arrayFloatAdd([1.2, 1, 2, 3, 4.2]));

    // ----------------字符处理----------------//
    formInputs2 = $("input");
    // console.log(formInputs2.length);
    for (var i = 0; i < formInputs2.length; i++) {
      var data = $(formInputs2[i]).text();
      var node = formInputs2[i];
    }
    var formInputs = $("input[class='form-control']");
    // console.log('formInputs', formInputs)
    var tmp = $("#addForm").serializeArray(); //表单序列化 = > 直接将表单的数据内容提取为查询字符串格式(键 = 值);
    var formatData1 = formatData(tmp); //格式化input数据
    // console.log('formdata1', formatData1);
    var formatData2 = JSON.stringify(formatData1); //转字符串json
    var formatData3 = JSON.parse(formatData2); //转json,
    var shortformatData = remove_empty(formatData3); //移除空字段//删除空数据字段，计算有效字段长度，添加json字段到数组
    // console.log('formdata2', shortformatData);
  } catch (error) {
    // errFlag = true;
    console.log(error);
    Toast("数据错误~", "error", 1000, 600, 50);
  } finally {
    // finallyCode - 无论 try / catch 结果如何都会执行的代码块\
    Toast("刷新计算~", "success", 1000, 500, 50);
  }
}

var OSSresult;
var iframeNmae = (window.frameElement && window.frameElement.id) || "noIframe";
// ------------------------10、提交项目定制---------开始--------修改和新增都在这提交-------//
$("#addSubmit").click(async function () {
  try {
    // 检查是否填完===================================================
    var isNotNullIputs = document.getElementsByClassName("notnull");
    var submitflag = true;
    var sinullFlag = true;
    for (var j = 0; j < isNotNullIputs.length; j++) {
      var inputValues = isNotNullIputs[j].value || ""; //获取了数据
      // console.log(inputValues)
      if (inputValues.length == 0 || typeof inputValues === undefined || inputValues === null) {
        sinullFlag = false;
        // console.log("没填完", inputValues)
        submitflag = false;
      } else {
        // console.log("全部填完", inputValues)
        // submitflag = true;
      }
    }
    if (sinullFlag == false) {
      narn("warn", "项目抬头有关键信息未填完，下方数值完全为空不能提交项目数据！", "警示");
    } else if (sinullFlag == true) {
      //iframeNmae == "iframe2" ||
      //==========================分组获取div 内容html-----------------------------------
      var addFormHtml = $("#addForm").html(); //字符串容易超出长度 一次性获取from表单元素内全部字符
      var FromTitelHtml1 = $("#FromTitel").html(); //获取整个页面文件字符串
      var bangjingHtml2 = $("#bangjing").html();
      var costTotalHtml3 = $("#costTotal").html();
      var renGongHtml4 = $("#renGong").html();
      var jietiHtml5 = $("#jieti").html();
      var OfferHtml6 = $("#Offer").html();
      var serviceHtml7 = $("#service").html();
      var OfferPricelHtml8 = $("#OfferPrice").html();
      var customerType2 = $("input[name='customerType']").val() || $("input[name='customerType']").attr("title");
      var ProjectTotalPrice2 = $("input[name='salesTotalPrice']").val();
      var engineer = $("input[name='engineer']").val();
      var projectName = $("input[name='projectName']").val();
      var projectNB = $("input[name='projectNB']").val();
      var other = $("input[name='other']").val();
      // var status = $("input[name='status']").val();
      // console.log("addFormHtml长度:", addFormHtml.length);
      var DesSumitData = {
        FromTitelHtml1,
      };
      var msg = "提醒！您真的确定立即提交修改吗？是否检查好内容无错误呢！\n\n请确认！";
      if (confirm(msg) == true) {
        //   $("#loading").fadeIn(1000);
        for (var key in DesSumitData) {
          //遍历去转文件流
          //   ----------------------转字符串到文件流--------addFormHtml----DesSumitData[key]----------
          var addformHTMLBlob = exportTxt(addFormHtml, key + ".txt");
          // console.log("addformHTMLBlob字节流长度：", parseFloat(addformHTMLBlob.size) / 1024);
        }
        var file = new File([addformHTMLBlob], "html.txt", {
          //字符串流转标准文件流包
          type: "text/plain",
          lastModified: Date.now(),
        });
        var fileNmae = "html.txt";
        //-------------------------异步将整个页面数据上传文件到OSS---------------------------//
        var promise = new Promise((resolve, reject) => {
          var dataString;

          function upload3(fileName, file) {
            //文件后缀类型、文件流、节点、旁边input元素
            // console.log("file字节流大小：", parseFloat(file.size) / 1024);
            try {
              var suffix = fileName.substr(fileName.indexOf("."));
              var obj = timestamp();
              var storeAs = "htmlData/" + obj + suffix;
              client
                .multipartUpload(storeAs, file)
                .then(function (result) {
                  var url = result.res.requestUrls[0];
                  var length = url.lastIndexOf("?");
                  OSSresult = result;
                  if (result.res.status == 200 || length == "-1") {
                    // console.log("oss上传成功");
                  } else {
                    Toast("上传失败！", "error", 2000);
                  }
                })
                .catch(function (err) {
                  console.log(err);
                  Toast("上传错误！", "error", 1000);
                })
                .finally(function (res) {
                  //执行完不管异常或正常都执行此方法
                  var json = {
                    uplodResultData: uplodResultData,
                    OSSresult: OSSresult,
                    res: res,
                  };
                  resolve(json);
                });
            } catch (error) {
              console.log(error);
            }
          }
          //   upload3(name, file);
          var uplodResultData2 = upload3("html.txt", file); //文件后缀类型、文件流 //上传文件
        });

        promise
          .then((arg) => {
            OSSresult = arg.OSSresult;
            var uplodResultUrl;
            //   console.log("OSSresult上传结果：", OSSresult);
            if (OSSresult.res.status == 200 || length == "-1") {
              //小于100kb返回的第一层结构中包含url，大于100kb返回结果在第二层中含有数组url
              var OSSresultRessUrls = OSSresult.res.requestUrls[0];
              // console.log("OSSresultRessUrls:", OSSresultRessUrls);
              var is100kb = OSSresultRessUrls.indexOf("?");
              if (is100kb == "-1") {
                uplodResultUrl = OSSresult.url; //直接获取外部url
                // console.log("小于100kb", is100kb, uplodResultUrl);
              } else {
                var qiepianUrlsArr = OSSresultRessUrls.split("?");
                uplodResultUrl = qiepianUrlsArr[0];
                // console.log("大于100KB", is100kb, uplodResultUrl);
              }
              // ----上传项目数据到服务器----- $("input[name='soft_cost_time']").val();
              var updataJosn = {
                ProjectTotalPrice: ProjectTotalPrice2,
                sid: $("#sid").html(),
                userType: getCookie("userType") || "user",
                engineer: getCookie("cname") || "",
                projectType: "定制",
                customerType: customerType2,
                engineer: engineer,
                projectName: projectName,
                desiProjectHtml: uplodResultUrl,
                projectNB: projectNB,
                status: "待审批",
                other,
                boxType1: trsBoxNames[0],
                boxType2: trsBoxNames[1],
                boxType3: trsBoxNames[2],
                boxType4: trsBoxNames[3],
                boxType5: trsBoxNames[4],
              };
              // console.log("上传定制项目返回：", updataJosn);
              if (iframeNmae == "iframe3") {
                var despath = "desiProjectApi";
              } else if (iframeNmae == "iframe2") {
                var despath = "updateProjecData";
              }
              // console.log("iframeNmae", iframeNmae);
              API.post(despath, updataJosn, function (res, status, err) {
                //接口返回数据、状态、错误-定制项目上传接口
                if (res.code == 200) {
                  window.parent.narn("success", "你刚提交的定制项目数据提交并保存成功", "结果提醒");
                  var clickPage = getCookie("clickPage") || 1;
                  window.parent.loadData(1, 10);
                  window.parent.windowParnet();
                  window.parent.nodeFrameget();
                } else {
                  console.log("提交失败", res);
                  narn("error", "你刚提交的定制项目数据提交失败", "结果提醒");
                }
              });
            } else {
              Toast("OSS上传失败！", "error", 2000);
            }
          })
          .catch((arg) => {
            console.log(`执行reject,参数是${arg}`);
            window.parent.narn("warn", "钣金数据开始不能全部为空！", "错误");
          })
          .finally(() => {
            //   console.log("结束promise");
          });
      } else {
        // alert(false);
        $("#loading").fadeOut(1000);
        Toast("请确认后再提交~", "warning", 800, 400);
      }
    }

    //-------------------------------表单序列号-----------------------------

    // var tmp = $("#addForm").serializeArray(); //tbody0
    var tmp = $("#tbody0").serializeArray(); //tbody0
    // console.log(tmp, tmp.length);
    var objData = formatData(tmp); //格式化数据
    // }
  } catch (error) {
    console.log(error);
  }
});
// -------------------------单击提交项目数据结束-----------------------//

// -----------------------onload后自动单独获取项目数据开始-------还需加新建项目时候区别执行-------------------------//// ---------------原生httpRquest-1---------------------//// -----------------------------------------------------
const p = new Promise(function (resolve, reject) {
  var iwindow = window.parent.$("#eidithModal"); //获取父级关闭他
  if (iframeNmae == "iframe") {
    //当前页面为查看定制项目数据
    // 准备获取定制项目数据-----------------------//
    var hash = self.location.hash; //哈希值只读取#之后的 , 获取地址中的sid
    cname = getCookie("cname");
    var i = hash.indexOf("=");
    var Hsid = hash.substring(i + 1, hash.length); //哈希里面不加#读不出sid
    const checkoneData = {
      ak: "13128755602",
      msg: "请求单个项目查看页面数据",
      sid: Hsid,
      getType: "descheckOne", //仅查看模式
      userName: getCookie("userName"),
      userType: getCookie("userType"),
    };
    var url = "checkone?sid=" + Hsid;
    var projectStatus;
    //   console.log("checkoneData", checkoneData);
    // // ---------------原生httpRquest-1---------------------//
    var objJson;
    ajax({
      url: url,
      type: "post",
      data: checkoneData,
      dataType: "json",
      timeout: 10000,
      contentType: "text/html; charset=utf-8Content-Type: multipart/form-data;boundary=something;",
      success: function (res) {
        objJson = JSON.parse(res);
        // console.log(res);
        // res.type = 2; //判断是修改类型就移除审批按钮
        if (objJson.code == 200) {
          objJson.flag = true; //按钮处理标记
          projectStatus = objJson.info[0].status;
          //   window.parent.narn("success", objJson.msg || "请求成功", "提示");

          resolve(objJson, 0);
        } else if (objJson.code == 100) {
        //   console.log(objJson.msg);
          Toast(objJson.msg, "error", 500, 800);
          objJson.flag = true;
          window.parent.narn("error", objJson.msg || "请求错误", "提示");

          //   resolve(objJson, 0);
        } else if (objJson.code == 101) {
        //   console.log(objJson);
          Toast(objJson.msg, "error", 500, 800);
          objJson.flag = true;
          window.parent.narn("error", objJson.msg || "请求错误", "提示");

          //   resolve(objJson, 0);
        } else {
        //   console.log(objJson);
          Toast(objJson.msg, "error", 500, 800);
          window.parent.narn("error", objJson.msg || "请求错误", "提示");
          //   reject(objJson);
        }
      },
      error: function (err) {
        //异常处理
        console.log(err);
        Toast(err, "error", 2000, 800);
        // reject(err);
      },
    });

    // --------------------------原生httpRquest2------------------------------------------// ----------------------------定制项目查看数据ajax请求-------------------------
    // 对迪form表单外部底部的按钮做处理
    $("#addSubmit").remove(); //禁用按钮
    $(".logoutBtn").hide();
    $(".abtn").hide();
    $("#file2").hide();
  } else if (iframeNmae == "iframe3") {
    //iframe3是新增定制项目，不做禁用按钮，不做数据加载
    // 新增定制项目，不做数据请求操作
    $(".logoutBtn").hide();
    var loading = $(window.parent.document).find("#loading");
    $(loading).hide();
    // console.log(iframeNmae, iwindow);
  } else if (iframeNmae == "iframe2") {
    //iframe2是修改不做禁用，
    // 准备获取定制项目数据-----------------------//
    var hash = self.location.hash; //哈希值只读取#之后的 ,
    cname = getCookie("cname");
    var i = hash.indexOf("=");
    var Hsid = hash.substring(i + 1, hash.length); //哈希里面不加#读不出sid
    const checkoneData = {
      ak: "13128755602",
      msg: "请求单个项目查看页面数据",
      sid: Hsid,
      //   getType: "descheckOne",
      getType: "change", //声明是修改数据会有权限检查
      userName: getCookie("userName"),
      came: getCookie("cname"),
      userType: getCookie("userType"),
    };
    var url2 = "checkone?sid=" + Hsid;

    // -----------------------------------------------------
    ajax({
      //请求数据浮动权限检查
      url: url2,
      type: "post",
      data: checkoneData,
      dataType: "json",
      timeout: 10000,
      contentType: "text/html; charset=utf-8Content-Type: multipart/form-data;boundary=something;",
      success: function (res) {
        res = JSON.parse(res);
        // console.log(res);
        res.type = 2; //判断是修改类型就移除审批按钮
        if (res.code == 200) {
          resolve(res);
        } else if (res.code == 100) {
        //   console.log(res);
          Toast(res.msg, "error", 500, 800);
          // res.flag = true;
          window.parent.narn("error", res.msg || "请求错误", "提示");
          window.parent.windowParnet();
          //   resolve(res);
        } else if (res.code == 101) {
          // console.log(res);
          //   alert(res.msg); //异常提示 只有在修改更新项目时候发现没权限弹窗提示
          window.parent.narn("error", res.msg || "修改错误", "提示");
          window.parent.layer.confirm(res.msg); //异常提示、 提示无限期修改或删除
          //    $(iwindow).click();
          //   $(iwindow).click(); //updateClose
          //   $(iwindow).css("display", "none");
          window.parent.windowParnet();
          Toast(res.msg, "error", 500, 800);
          // res.flag = true;
          // resolve(res);
          // reject(res.msg);
        } else {
          console.log(res);
          window.parent.narn("error", res.msg || "修改错误", "提示");
        }
      },
      //异常处理
      error: function (err) {
        console.log(err);
        Toast(err, "error", 500, 800);
        window.parent.narn("error", err || "错误", "提示");
        // reject(err);
      },
    });
    // // ---------------原生httpRquest-1---------------------//

    // -----------------------httpRquest1----------------------------------------
    $(".logoutBtn").hide();
    $("#auditing").remove();
  } else if (iframeNmae == "noIframe") {
    //独立页面查看数据，对底部按钮处理
    // console.log("iframeNmae", iframeNmae);
    // 准备获取定制项目数据-----------------------//
    var hash = self.location.hash; //哈希值只读取#之后的 ,
    cname = getCookie("cname");
    var i = hash.indexOf("=");
    var Hsid = hash.substring(i + 1, hash.length); //哈希里面不加#读不出sid
    // console.log(hash, Hsid);
    const checkoneData = {
      ak: "13128755602",
      msg: "请求单个项目查看页面数据",
      sid: Hsid,
      getType: "descheckOne",
      userName: getCookie("userName"),
      userType: getCookie("userType"),
    };
    var url = "checkone?sid=" + Hsid;
    // // ---------------原生httpRquest-1---------------------//
    var objJson;
    ajax({
      url: url,
      type: "post",
      data: checkoneData,
      dataType: "json",
      timeout: 10000,
      contentType: "text/html; charset=utf-8Content-Type: multipart/form-data;boundary=something;",
      success: function (res) {
        res = JSON.parse(res);
        // console.log(res);
        // res.type = 2; //判断是修改类型就移除审批按钮
        if (res.code == 200) {
          //   console.log(res);
          res.flag = true;
          //   console.log(" res.flag", res);
          resolve(res);
        } else if (res.code == 100) {
          console.log(res.msg);
          Toast(res.msg, "error", 500, 800);
          window.parent.narn("error", res.msg || "错误", "提示");
          console.log(res);
          res.flag = true;
          return res;
          //   resolve(res);
        } else if (res.code == 101) {
          console.log(res);
          console.log(res);
          Toast(res.msg, "error", 500, 800);
          window.parent.narn("error", res.msg || "错误", "提示");
          res.flag = true;
          return res;
          //   resolve(res);
        } else {
          console.log(res);
          Toast(err, "error", 500, 800);
          window.parent.narn("error", res.msg || "错误", "提示");
          return res;
          //   reject(err);
        }
      },
      error: function (err) {
        //异常处理
        console.log(err);
        Toast(err, "error", 500, 800);
        window.parent.narn("error", err || "错误", "提示");
        // reject(err);
      },
    });
    // --------------------------原生httpRquest2------------------------------------------

    // 对迪form表单外部底部的按钮做处理
    // var str = `<button class="btn btn-info" id="auditing" type="button" title="领导审核审批！">审核</button>`;
    // $("#submitDiv").prepend(str);
    $("#addSubmit").remove(); //禁用按钮
    $(".Close").remove(); //禁用按钮
  }
});
p.then(
  //异步函数主方法执行完成后的回调函数
  function (promisRes) {
    // 异步获取定制项目数据成功后，接收resolve传来的数据，对其项目数据字符串数据请求获取
    var desDataURL = promisRes.info[0].desiProjectHtml || "";
    $("#sid").html(promisRes.info[0].sid);
    // console.log(desDataURL);
    var url = desDataURL; // "http://zhilai-baojia.oss-cn-shenzhen.aliyuncs.com/img/20220701202711.txt"; //uplodResultUrl; //
    var htmlobj = $.ajax({
      url: url,
      async: true,
      datatype: "text",
      method: "get",
      complete: function (res) {
        // if (res.code == 200) {//OSS请求返回没有状态码
        // Toast("请求项目数据完成", "success", 1000, 1050, 100);
        $("#loading").fadeOut();
        var uploadResStr = res.responseText;
        // console.log(uploadResStr);
        // $("#addForm").html("");
        $("#addForm").empty();
        // setTimeout(() => {
        $("#addForm").append(uploadResStr); //插入定制项目全部数据
        scal();
        // console.log(res);
        // }, 1);

        // -------------对input 按不同情况做禁止编辑处理--------------
        if (promisRes.flag) {
          $("input").attr("disabled", "disabled"); //仅读
          $("input").addClass("disabledCss"); //仅读
          $("#addForm button").attr("disabled", "disabled"); //禁用全部按钮 //只有底部按钮在addform之外才能用
          $("#Refresh").remove(); //禁用按钮
          $("#addSubmit").attr("disabled", "disabled"); //禁用按钮
        }

        // 将某些显示很长单元格内容添加到title里面提示
        var titelToasts = $(".titelToast");
        for (var key = 0; key < titelToasts.length; key++) {
          // console.log(titelToasts)
          var varTitel = $(titelToasts[key]).html() || $(titelToasts[key]).text() || $(titelToasts[key]).val();
          $(titelToasts[key]).attr("title", varTitel);
          // console.log(varTitel)
        }
        // }else{
        //  window.parent.narn("success", res, "提示");
        // }
        if (iframeNmae == "noIframe" || iframeNmae == "iframe") {
          $("#file2").hide();
        }
      },
    });
    if (promisRes.info[0].status == "待审批" && promisRes.type !== 2) {
      var str = `<button class="btn btn-info" id="auditing" type="button" title="领导审核审批！">审核</button>`;
      // $("#submitDiv").prepend(str);
      $("#auditing").show();
    } else if (promisRes.info[0].status == "已审批") {
      var str =
        ` <!-- 审批盖章元素 -->
        <div class="auditing seal" style="display:none; margin-bottom:200px;left:85%">
            <div class="seal-son">
                <span class="Approver trs45">` +
        promisRes.info[0].Approver +
        `</span>
                <span class="trs45" style=" font-weight: 900;">已审批!</span>
                <span class="Approvertime  trs45" style="">2021.08.09 23:59:00</span>
            </div>
        </div>`;
      $(".mainBody").append(str);
      $(".auditing").show();
    }
  }
  //   function (err) {
  //     // 接收reject传来的数据，做些什么
  //     console.log(err);
  //     window.parent.narn("error", err, "提示");
  //   }
);
p.catch(function (err) {
  // 接收reject传来的数据或者捕捉到then()中的运行报错时，做些什么
  console.log(err);
  window.parent.narn("error", err, "提示");
  return err;
});
p.finally(function (res) {
  scal();
  // console.log(res);
  // 不管什么状态都执行
});

// ----------------定制项目审批方法---------------------//
$("#auditing").on("click", function (e) {
  //   console.log("审批");
  try {
    var hash = self.location.hash; //哈希值只读取#之后的
    var i = hash.indexOf("=");
    var Hsid = hash.substring(i + 1, hash.length); //哈希里面不加#读不出sid
    var url = "/auditing";
    var subData = {
      sid: Hsid,
      cname: cname,
    };
    $.post(url, subData, function (res, status, err) {
      //   console.log(res);
      if (res.code == 200) {
        new Promise(function (resolve, reject) {
          setTimeout(function () {
            // console.log('First');
            Toast(res.msg, "success", 1000, 500);
            resolve();
          }, 1);
        })
          .then(function () {
            return new Promise(function (resolve, reject) {
              setTimeout(function () {
                // console.log("Second");
                $("#auditing").hide(1);
                resolve();
              }, 1);
            });
          })
          .then(function () {
            return new Promise(function (resolve, reject) {
              setTimeout(function () {
                // console.log("Third");
                $(".Approver").html(cname);
                var str =
                  ` <!-- 审批盖章元素 -->
        <div class="auditing seal" style="display:none; margin-bottom:200px;left:85%">
            <div class="seal-son">
                <span class="Approver trs45">` +
                  cname +
                  `</span>
                <span class="trs45" style=" font-weight: 900;">已审批!</span>
                <span class="Approvertime  trs45" style="">2021.08.09 23:59:00</span>
            </div>
        </div>`;
                $(".mainBody").append(str);
                $(".auditing").show();
                resolve();
              }, 100);
            });
          })
          .then(function () {
            setTimeout(function () {
              // console.log("four");
              var close = window.parent.document.getElementById("close");
              // console.log(close)
              var clickPage = getCookie("clickPage") || 1;
              $(close).click();
              if (self.frameElement && self.frameElement.tagName == "IFRAME") {
                window.parent.loadData(clickPage, 10);
                // console.log("在ifrmae中");
                window.parent.narn("success", "审批成功", "提示");
              } else {
                // loadData(clickPage, 10);
                // console.log("不在ifrmae中");
                narn("success", "审批成功", "提示");
              }
            }, 100);
          });
      } else if (res.code == 101 || res.code == 100) {
        Toast("审批结果:" + res.msg, "error", 2000, 1000, 50);
      } else {
        console.log(res, err, status);
        Toast(err, "error", 500, 500);
      }
    });
  } catch (error) {
    Toast(error, "error", 2000, 500);
  }
});

// -------------------审批方法结束--------------------------------//

// /-----------------------------字符串转blob---------------------//
function exportTxt(text, filename) {
  //字符串转blob
  const eleLink = document.createElement("a");
  eleLink.download = filename;
  eleLink.style.display = "none";
  // 将内容转为 blob
  const blob = new Blob([text]);
  eleLink.href = URL.createObjectURL(blob);
  document.body.appendChild(eleLink);
  // eleLink.click();
  document.body.removeChild(eleLink);
  return blob;
}

// ----------------------表单数据处理// 清除非法字符，同时计算字段数量---------------------
var jsonLength, jsonLength2; //有效字段数和总字段数
var submitDataJsonArr = [];

function remove_empty(obj) {
  // rote = $("#rote").val(); //获取毛利率 直接获取数据
  // Server_rote = $("#Server_rote").val(); //获取服务费率
  sid = $("#sid").html(); //获取sid
  // window.API["rote"] = rote || 40;
  // window.API["Server_rote"] = Server_rote || 2;
  window.API["sid"] = sid.toString();
  window.API["status"] = "待审批";
  window.API["userType"] = getCookie("userType");
  window.API["cname"] = getCookie("cname");
  window.API["engineer"] = getCookie("cname"); //登录后会有本地写入姓名
  // window.API["customerType"] = $("input[name='customerType']").val() || '利润客户';
  // console.log(window.API["customerType"], $("input[name='customerType']").val())
  jsonLength2 = 0;
  jsonLength = 0;
  submitDataJsonArr = [];
  // obj.ak = API.ak; //添加ak
  // obj.rote = API.rote;
  // obj.Server_rote = API.Server_rote;
  obj.sid = API.sid;
  // obj.other = API.other;
  obj.status = API.status;
  obj.userType = API.userType;
  obj.engineer = API.engineer;
  // obj.customerType = API.customerType;
  // console.log(obj.sid, obj.rote, obj.other);
  var obj2 = {}; //临时json容器 装全部字段
  for (let k in obj) {
    v = obj[k];
    if (v === "" || v === null || v === NaN || v === undefined || isNaN(v)) {
      delete obj[k];
      // console.log(v)
      // console.log(k)
    } else {
      // console.log(k, ':', v);//键值
      // console.log(k);//键名
      obj2[k] = v; //bij对象数据的键名在用变量代替时候需要用下标而不是点
      jsonLength++;
      submitDataJsonArr.push(obj2);
    }
    jsonLength2++; //总字段数
    obj2[k] = v;
  }
  // console.log(jsonLength, jsonLength2);
  // obj.totalDataCount = jsonLength;//剔除为空的字段
  // obj2.totalDataCount = jsonLength2;//JSON全字段返回
  return obj;
}

// 判断内容是否为空------------------------
function isStr(str) {
  if (str == "" || str == null || isNaN(str) || str == undefined || isnUll(str)) {
    //不能用isNaN
    return 0;
  } else {
    return str;
  }
}

// 点击计算触发提示方法，弥补onchange内容改变事件不能在触发后获取当前输入的数据的缺陷，
$("#scal").click(function (e) {
  scal(e);
});

// 阻止回车事件
document.onkeydown = function () {
  if (window.event && window.event.keyCode == 13) {
    window.event.returnValue = false;
  }
};

// 单击底部关闭按钮
$(".Close").bind("click", function (event) {
  if (event && event.stopPropagation) {
    event.stopPropagation();
  } else {
    event.cancelBubble = true;
  }
  //   console.log(event);
  //获取父级IFRAME窗口内模态框元素关闭
  //   window.parent.windowParnet();
  window.parent.windowParnet(".modal");
});

// ===========================输入规范及限制处理===============================//
// 现在输入中文==============================
$("body ").on("change", "input.size", function (e) {
  var str = $(this).val();
  var str2 = str.replace(/[\u0391-\uFFE5]/gi, "");
  $(this).val(str2);
  // console.log(str2);
});

// $("body").on("blur", "input.boxSN", function (e) {
$("body").on("change", "input.boxSN", function (e) {
  var str = $(this).val();
  var str2 = str.replace(/[\u0391-\uFFE5]/gi, "");
  $(this).val(str2);
  // console.log(str2);
});
// input输入事件 刷新计算
$("body").on("change", "input", function (e) {
  scal(e);
});
// ===========================输入规范及限制处理===============================//

//===========================================键盘监听事件======================================
$(document).keydown(function (event) {
  //   event.preventDefault();
  if (event.keyCode == 13) {
  } else if (event.keyCode == 27) {
    //ESC键盘
    window.parent.windowParnet();
  }
});

// ==========================表格导入==================
$("#daoru").click(function (e) {
  //   $("#excel-file").trigger("click");
  excelFileChange(e, "designer");
});
